package com.sambo.inspection.http;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.HttpHeaders;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.utils.OkLogger;
import com.sambo.inspection.bean.GlobleBean;
import com.sambo.inspection.util.JsonUtil;

import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class HttpClient {

    private static final String OS = "android";

    public interface NetworkUnavailableListener {
        void networkUnavailable();
    }

    public static String get(Context context, String path, Map<String, String> params, HttpResponseHandler responseHandler, NetworkUnavailableListener listener) {
        if (context == null) {
            return null;
        }
        if (!isNetworkConnect(context)) {
            if (listener != null) {
                listener.networkUnavailable();
            }
            return null;
        }

        params.put("os", OS);

        if (GlobleBean.getInstance().getUserID() != 0) {
            params.put("userId", String.valueOf(GlobleBean.getInstance().getUserID()));
        }

        if (!TextUtils.isEmpty(GlobleBean.getInstance().getUserName())) {
            params.put("username", GlobleBean.getInstance().getUserName());
        }

        if (!TextUtils.isEmpty(GlobleBean.getInstance().getAccessToken())) {
            params.put("access_token", GlobleBean.getInstance().getAccessToken());
        }

        String requestUrl = createUrlFromParams(path, params);

        String tag = getGUID() + path;

        OkGo.<String>get(requestUrl)
                .cacheKey(path)
                .tag(tag)
                .execute(responseHandler);
        return tag;
    }

    public static String post(Context context, String path, Object jsonBean, HttpResponseHandler responseHandler, NetworkUnavailableListener listener) {
        if (context == null) {
            return null;
        }
        if (!isNetworkConnect(context)) {
            if (listener != null) {
                listener.networkUnavailable();
            }
            return null;
        }

        String requestUrl = editQueryString(path);

        BaseRequest request = new BaseRequest();
        request.setData(jsonBean);
        request.setOperationType("");
        request.setProcessDefinitionId("");
        request.setUserid(String.valueOf(GlobleBean.getInstance().getUserID()));
        request.setUsername(GlobleBean.getInstance().getUserName());

        String tag = getGUID() + requestUrl;

        OkGo.<String>post(requestUrl)
                .cacheKey(requestUrl)
                .tag(tag)
                .upJson(JsonUtil.toJson(request))
                .execute(responseHandler);
        return tag;
    }

    public static String post(Context context, String path, HttpParams params, HttpResponseHandler responseHandler, NetworkUnavailableListener listener) {
        if (context == null) {
            return null;
        }
        if (!isNetworkConnect(context)) {
            if (listener != null) {
                listener.networkUnavailable();
            }
            return null;
        }

        String requestUrl = editQueryString(path);

        String tag = getGUID() + requestUrl;

        OkGo.<String>post(requestUrl)
                .cacheKey(requestUrl)
                .tag(tag)
                .params(params)
                .execute(responseHandler);
        return tag;
    }

    public static String upload(Context context, String path, HttpParams params, HttpResponseHandler responseHandler, NetworkUnavailableListener listener) {
        if (context == null) {
            return null;
        }
        if (!isNetworkConnect(context)) {
            if (listener != null) {
                listener.networkUnavailable();
            }
            return null;
        }

        String requestUrl = editQueryString(path);

        String tag = getGUID() + requestUrl;

        OkGo.<String>post(path)
                .isMultipart(true)
                .headers(HttpHeaders.HEAD_KEY_ACCEPT, "application/json, */*")
                .headers(HttpHeaders.HEAD_KEY_ACCEPT_ENCODING, HttpHeaders.HEAD_VALUE_ACCEPT_ENCODING)
                .headers(HttpHeaders.HEAD_KEY_CONNECTION, HttpHeaders.HEAD_VALUE_CONNECTION_KEEP_ALIVE)
                .tag(tag)
                .params(params)
                .execute(responseHandler);
        return tag;
    }

    public static void cancelRequest(String tag) {
        OkGo.getInstance().cancelTag(tag);
    }

    public static boolean isNetworkConnect(Context context) {
        ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo mobileInfo = conMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        NetworkInfo wifiInfo = conMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

        if (mobileInfo != null) {
            NetworkInfo.State mobileState = mobileInfo.getState();
            if (mobileState != null && (mobileState == NetworkInfo.State.CONNECTED || mobileState == NetworkInfo.State.CONNECTING)) {
                return true;
            }
        }

        if (wifiInfo != null) {
            NetworkInfo.State wifiState = conMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
            if (wifiState != null && (wifiState == NetworkInfo.State.CONNECTED || wifiState == NetworkInfo.State.CONNECTING)) {
                return true;
            }
        }

        return false;
    }

    /**
     * 生成GUID
     * @return GUID
     */
    public static String getGUID() {

        UUID uuid = UUID.randomUUID();
        // 转换为小写并替换"-"
        return uuid.toString().toLowerCase().replaceAll("-", "");
    }

    /** 将传递进来的参数拼接成 url */
    public static String createUrlFromParams(String url, Map<String, String> params) {
        try {
            StringBuilder sb = new StringBuilder();
            sb.append(url);
            if (url.indexOf('&') > 0 || url.indexOf('?') > 0) sb.append("&");
            else sb.append("?");
            for (Map.Entry<String, String> urlParams : params.entrySet()) {
                //对参数进行 utf-8 编码,防止头信息传中文
                String urlValue = URLEncoder.encode(urlParams.getValue(), "UTF-8");
                sb.append(urlParams.getKey()).append("=").append(urlValue).append("&");
            }
            sb.deleteCharAt(sb.length() - 1);
            return sb.toString();
        } catch (UnsupportedEncodingException e) {
            OkLogger.printStackTrace(e);
        }
        return url;
    }

    private static String editQueryString(String path) {
        String queryString = path + "?os=" + OS;

        if (!TextUtils.isEmpty(GlobleBean.getInstance().getUserName())) {
            queryString = queryString + "&username=" + GlobleBean.getInstance().getUserName();
        }

        if (GlobleBean.getInstance().getUserID() != 0) {
            queryString = queryString + "&userId=" + GlobleBean.getInstance().getUserID();
        }

        if (!TextUtils.isEmpty(GlobleBean.getInstance().getAccessToken())) {
            queryString = queryString + "&access_token=" + GlobleBean.getInstance().getAccessToken();
        }

        return queryString;
    }

}
